// subscription-list.js
Page({
  data: {
    subscriptions: [],
    totalAmount: 0,
    showAddModal: false,
    showEditModal: false,
    showChatModal: false,
    currentEditIndex: -1,
    chatMessages: [],
    chatInput: '',
    isAIThinking: false,
    parsedData: null,
    formData: {
      name: '',
      price: '',
      cycle: 'month', // month, year
      nextRenewalDate: '',
      category: 'entertainment', // entertainment, work, life, education, other
      description: ''
    },
    cycleOptions: [
      { label: '按月', value: 'month' },
      { label: '按年', value: 'year' }
    ],
    categoryOptions: [
      { label: '娱乐', value: 'entertainment', icon: '娱', color: '#F59E0B' },
      { label: '工作', value: 'work', icon: '工', color: '#3B82F6' },
      { label: '生活', value: 'life', icon: '生', color: '#10B981' },
      { label: '教育', value: 'education', icon: '教', color: '#8B5CF6' },
      { label: '其他', value: 'other', icon: '其', color: '#6B7280' }
    ],
    cycleIndex: 0,
    categoryIndex: 0
  },

  onLoad() {
    // 初始化模拟数据（仅在没有数据时）
    this.initMockData()
    this.loadSubscriptions()
  },

  // 初始化模拟数据
  initMockData() {
    const existingData = wx.getStorageSync('subscriptions')
    if (!existingData || existingData.length === 0) {
      const today = new Date()
      const mockData = [
        {
          id: 1,
          name: 'Netflix 会员',
          price: 15.99,
          cycle: 'month',
          nextRenewalDate: this.getDateString(today, 5),
          category: 'entertainment',
          description: '流媒体视频服务',
          createTime: new Date().toISOString()
        },
        {
          id: 2,
          name: 'Spotify Premium',
          price: 9.99,
          cycle: 'month',
          nextRenewalDate: this.getDateString(today, 12),
          category: 'entertainment',
          description: '音乐流媒体服务',
          createTime: new Date().toISOString()
        },
        {
          id: 3,
          name: 'Adobe Creative Cloud',
          price: 52.99,
          cycle: 'month',
          nextRenewalDate: this.getDateString(today, 20),
          category: 'work',
          description: '设计软件套装',
          createTime: new Date().toISOString()
        },
        {
          id: 4,
          name: 'Microsoft 365',
          price: 69.99,
          cycle: 'year',
          nextRenewalDate: this.getDateString(today, 60),
          category: 'work',
          description: '办公软件套装',
          createTime: new Date().toISOString()
        },
        {
          id: 5,
          name: 'Apple iCloud+',
          price: 6.00,
          cycle: 'month',
          nextRenewalDate: this.getDateString(today, 2),
          category: 'life',
          description: '云存储服务',
          createTime: new Date().toISOString()
        },
        {
          id: 6,
          name: 'Coursera Plus',
          price: 399.00,
          cycle: 'year',
          nextRenewalDate: this.getDateString(today, 90),
          category: 'education',
          description: '在线学习平台',
          createTime: new Date().toISOString()
        },
        {
          id: 7,
          name: 'Amazon Prime',
          price: 14.99,
          cycle: 'month',
          nextRenewalDate: this.getDateString(today, 8),
          category: 'life',
          description: '电商会员服务',
          createTime: new Date().toISOString()
        }
      ]
      wx.setStorageSync('subscriptions', mockData)
    }
  },

  // 获取日期字符串（今天 + 天数）
  getDateString(baseDate, daysLater) {
    const date = new Date(baseDate)
    date.setDate(date.getDate() + daysLater)
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const monthStr = month < 10 ? '0' + month : String(month)
    const dayStr = day < 10 ? '0' + day : String(day)
    return year + '-' + monthStr + '-' + dayStr
  },

  onShow() {
    this.loadSubscriptions()
  },

  // 获取分类配置
  getCategoryConfig(category) {
    const configs = {
      entertainment: { icon: '娱', color: '#FEF3C7' },
      work: { icon: '工', color: '#DBEAFE' },
      life: { icon: '生', color: '#D1FAE5' },
      education: { icon: '教', color: '#E9D5FF' },
      other: { icon: '其', color: '#F3F4F6' }
    }
    return configs[category] || configs.other
  },

  // 加载订阅列表
  loadSubscriptions() {
    let subscriptions = wx.getStorageSync('subscriptions') || []
    // 按创建时间倒序排序（新添加的在最上面）
    subscriptions.sort((a, b) => {
      const timeA = a.createTime ? new Date(a.createTime).getTime() : 0
      const timeB = b.createTime ? new Date(b.createTime).getTime() : 0
      return timeB - timeA // 倒序，新的在前
    })
    
    // 处理数据，添加格式化字段
    subscriptions = subscriptions.map(item => {
      const categoryConfig = this.getCategoryConfig(item.category)
      const days = this.getDaysUntilRenewal(item.nextRenewalDate)
      let daysText = ''
      let daysColor = '#6B7280'
      
      if (days < 0) {
        daysText = `已过期${Math.abs(days)}天`
        daysColor = '#EF4444'
      } else if (days === 0) {
        daysText = '今天到期'
        daysColor = '#F59E0B'
      } else if (days <= 7) {
        daysText = `还有${days}天`
        daysColor = '#F59E0B'
      } else {
        daysText = `还有${days}天`
        daysColor = '#10B981'
      }

      return {
        id: item.id,
        name: item.name,
        price: item.price,
        cycle: item.cycle,
        nextRenewalDate: item.nextRenewalDate,
        category: item.category,
        description: item.description,
        createTime: item.createTime,
        categoryIcon: categoryConfig.icon,
        categoryColor: categoryConfig.color,
        formattedDate: this.formatDate(item.nextRenewalDate),
        daysText: daysText,
        daysColor: daysColor
      }
    })

    // 计算总金额（按月计算）
    const totalAmount = subscriptions.reduce((sum, item) => {
      const monthlyPrice = item.cycle === 'year' ? item.price / 12 : item.price
      return sum + monthlyPrice
    }, 0)

    this.setData({
      subscriptions,
      totalAmount: totalAmount.toFixed(2)
    })
  },

  // 显示添加弹窗（对话形式）
  showAddDialog() {
    const welcomeMessage = {
      type: 'ai',
      content: '你好！请告诉我你开通了什么会员服务，比如"我开了Netflix会员，每月15.99元"，我会自动帮你整理并归类。',
      timestamp: new Date().getTime()
    }
    this.setData({
      showChatModal: true,
      chatMessages: [welcomeMessage],
      chatInput: '',
      isAIThinking: false,
      parsedData: null
    })
  },

  // 显示编辑弹窗
  showEditDialog(e) {
    const index = e.currentTarget.dataset.index
    const subscription = this.data.subscriptions[index]
    const cycleIndex = subscription.cycle === 'month' ? 0 : 1
    const categoryIndex = this.data.categoryOptions.findIndex(opt => opt.value === subscription.category)
    
    this.setData({
      showEditModal: true,
      currentEditIndex: index,
      cycleIndex,
      categoryIndex: categoryIndex >= 0 ? categoryIndex : 0,
      formData: {
        name: subscription.name,
        price: subscription.price.toString(),
        cycle: subscription.cycle,
        nextRenewalDate: subscription.nextRenewalDate,
        category: subscription.category,
        description: subscription.description || ''
      }
    })
  },

  // 关闭弹窗
  closeModal() {
    this.setData({
      showAddModal: false,
      showEditModal: false,
      showChatModal: false,
      currentEditIndex: -1,
      chatMessages: [],
      chatInput: '',
      parsedData: null
    })
  },

  // 表单输入
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 选择续期日期
  onDateChange(e) {
    this.setData({
      'formData.nextRenewalDate': e.detail.value
    })
  },

  // 选择周期
  onCycleChange(e) {
    const index = parseInt(e.detail.value)
    const cycle = this.data.cycleOptions[index].value
    this.setData({
      cycleIndex: index,
      'formData.cycle': cycle
    })
  },

  // 选择分类
  onCategoryChange(e) {
    const index = parseInt(e.detail.value)
    const category = this.data.categoryOptions[index].value
    this.setData({
      categoryIndex: index,
      'formData.category': category
    })
  },

  // 保存订阅
  saveSubscription() {
    const { formData, subscriptions, currentEditIndex } = this.data
    
    if (!formData.name || !formData.price || !formData.nextRenewalDate) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      })
      return
    }

    const subscription = {
      id: currentEditIndex >= 0 ? subscriptions[currentEditIndex].id : Date.now(),
      name: formData.name,
      price: parseFloat(formData.price),
      cycle: formData.cycle,
      nextRenewalDate: formData.nextRenewalDate,
      category: formData.category,
      description: formData.description,
      createTime: currentEditIndex >= 0 ? subscriptions[currentEditIndex].createTime : new Date().toISOString()
    }

    let newSubscriptions = []
    for (let i = 0; i < subscriptions.length; i++) {
      newSubscriptions.push(subscriptions[i])
    }
    if (currentEditIndex >= 0) {
      newSubscriptions[currentEditIndex] = subscription
    } else {
      newSubscriptions.push(subscription)
    }

    wx.setStorageSync('subscriptions', newSubscriptions)
    this.loadSubscriptions()
    this.closeModal()
    wx.showToast({
      title: currentEditIndex >= 0 ? '修改成功' : '添加成功',
      icon: 'success'
    })
  },

  // 删除订阅
  deleteSubscription(e) {
    const index = e.currentTarget.dataset.index
    const subscription = this.data.subscriptions[index]
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${subscription.name}"吗？`,
      success: (res) => {
        if (res.confirm) {
          const subscriptions = this.data.subscriptions.filter((_, i) => i !== index)
          wx.setStorageSync('subscriptions', subscriptions)
          this.loadSubscriptions()
          wx.showToast({
            title: '删除成功',
            icon: 'success'
          })
        }
      }
    })
  },

  // 计算距离续期天数
  getDaysUntilRenewal(dateStr) {
    const today = new Date()
    today.setHours(0, 0, 0, 0)
    const renewalDate = new Date(dateStr)
    renewalDate.setHours(0, 0, 0, 0)
    const diffTime = renewalDate - today
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    return diffDays
  },

  // 格式化日期
  formatDate(dateStr) {
    const date = new Date(dateStr)
    const month = date.getMonth() + 1
    const day = date.getDate()
    return `${month}月${day}日`
  },

  // 对话输入
  onChatInput(e) {
    this.setData({
      chatInput: e.detail.value
    })
  },

  // 发送消息
  sendMessage() {
    const input = this.data.chatInput.trim()
    if (!input || this.data.isAIThinking) return

    // 添加用户消息
    const userMessage = {
      type: 'user',
      content: input,
      timestamp: new Date().getTime()
    }

    const messages = [...this.data.chatMessages, userMessage]
    this.setData({
      chatMessages: messages,
      chatInput: '',
      isAIThinking: true
    })

    // 调用AI解析
    this.parseWithAI(input)
  },

  // 使用AI解析用户输入
  parseWithAI(userInput) {
    const prompt = `请从以下用户输入中提取订阅服务信息，并以JSON格式返回：
用户输入："${userInput}"

请提取以下信息：
1. name: 服务名称（必填）
2. price: 价格数字（必填，只返回数字）
3. cycle: 计费周期，只能是"month"或"year"（必填）
4. category: 分类，只能是"entertainment"、"work"、"life"、"education"、"other"之一（必填）
5. description: 简短描述（可选）

如果信息不完整，请根据常识推断。例如：
- 视频流媒体、音乐、游戏等归为"entertainment"
- 办公软件、设计工具等归为"work"
- 云存储、电商会员等归为"life"
- 在线课程、学习平台归为"education"

只返回JSON对象，不要其他文字。格式示例：
{"name":"Netflix会员","price":15.99,"cycle":"month","category":"entertainment","description":"流媒体视频服务"}`

    wx.request({
      url: 'https://api.deepseek.com/v1/chat/completions',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-68587461c88d4e1ab52f51fde28805ae'
      },
      data: {
        model: 'deepseek-chat',
        messages: [
          {
            role: 'user',
            content: prompt
          }
        ],
        temperature: 0.3,
        max_tokens: 300
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data && res.data.choices && res.data.choices.length > 0) {
          const content = res.data.choices[0].message.content.trim()
          // 尝试提取JSON
          let jsonStr = content
          const jsonMatch = content.match(/\{[\s\S]*\}/)
          if (jsonMatch) {
            jsonStr = jsonMatch[0]
          }

          try {
            const parsed = JSON.parse(jsonStr)
            this.handleParsedData(parsed, userInput)
          } catch (e) {
            console.error('JSON解析失败:', e)
            this.handleParseError(userInput)
          }
        } else {
          this.handleParseError(userInput)
        }
      },
      fail: (err) => {
        console.error('API调用失败:', err)
        this.handleParseError(userInput)
      }
    })
  },

  // 处理解析成功的数据
  handleParsedData(parsed, userInput) {
    // 验证必要字段
    if (!parsed.name || !parsed.price) {
      this.handleParseError(userInput)
      return
    }

    // 设置默认值
    const today = new Date()
    const nextRenewalDate = this.getDateString(today, 30) // 默认30天后

    const subscriptionData = {
      name: parsed.name,
      price: parseFloat(parsed.price),
      cycle: parsed.cycle || 'month',
      category: parsed.category || 'other',
      description: parsed.description || '',
      nextRenewalDate: nextRenewalDate
    }

    // 获取分类名称
    const categoryOption = this.data.categoryOptions.find(opt => opt.value === subscriptionData.category)
    const categoryName = categoryOption ? categoryOption.label : '其他'

    // AI回复消息
    const aiMessage = {
      type: 'ai',
      content: `好的，我已经识别出以下信息：\n\n服务名称：${subscriptionData.name}\n价格：¥${subscriptionData.price}/${subscriptionData.cycle === 'month' ? '月' : '年'}\n分类：${categoryName}\n续期日期：${this.formatDate(nextRenewalDate)}\n\n请确认信息是否正确，或告诉我需要修改的地方。`,
      timestamp: new Date().getTime()
    }

    const messages = [...this.data.chatMessages, aiMessage]
    this.setData({
      chatMessages: messages,
      isAIThinking: false,
      parsedData: subscriptionData
    })
  },

  // 处理解析错误
  handleParseError(userInput) {
    const aiMessage = {
      type: 'ai',
      content: '抱歉，我没有完全理解你的信息。请重新描述，格式如："我开了Netflix会员，每月15.99元"或"我订阅了Adobe Creative Cloud，52.99元一个月"。',
      timestamp: new Date().getTime()
    }

    const messages = [...this.data.chatMessages, aiMessage]
    this.setData({
      chatMessages: messages,
      isAIThinking: false
    })
  },

  // 确认添加订阅
  confirmAddSubscription() {
    if (!this.data.parsedData) {
      wx.showToast({
        title: '请先完成对话',
        icon: 'none'
      })
      return
    }

    const subscriptions = wx.getStorageSync('subscriptions') || []
    const newSubscription = {
      id: Date.now(),
      name: this.data.parsedData.name,
      price: this.data.parsedData.price,
      cycle: this.data.parsedData.cycle,
      nextRenewalDate: this.data.parsedData.nextRenewalDate,
      category: this.data.parsedData.category,
      description: this.data.parsedData.description,
      createTime: new Date().toISOString()
    }

    subscriptions.push(newSubscription)
    wx.setStorageSync('subscriptions', subscriptions)
    
    this.loadSubscriptions()
    this.closeModal()
    
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
})
